package com.cans.lightning.business.lowcode.service.impl;

import com.cans.lightning.business.lowcode.dao.AppIndexDao;
import com.cans.lightning.business.lowcode.entity.AppIndex;
import com.cans.lightning.business.lowcode.enums.AppIndexEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author cans
 * @date 2022/11/6
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class AppIndexServiceImpl {

    @Resource
    private AppIndexDao appIndexDao;

    public Long getNextMainTableIndex(){
        return this.getNextFieldIndex(AppIndexEnum.MAIN_TABLE.getKey());
    }

    public Long getNextSonTableIndex(){
        return this.getNextFieldIndex(AppIndexEnum.SON_TABLE.getKey());
    }

    public Long getNextFieldIndex(String tableId) {
        AppIndex appIndex = appIndexDao.createLambdaQuery().andEq(AppIndex::getName, tableId).asc(AppIndex::getCreateTime).single();
        if(appIndex == null){
            appIndex = new AppIndex();
            appIndex.setName(tableId);
            appIndex.setValue(0L);
            appIndexDao.insert(appIndex);
        }else{
            appIndex.setValue(appIndex.getValue()+ 1);
            appIndexDao.updateById(appIndex);
        }
        return appIndex.getValue();
    }
}
